{extend name="base" /}
{block name="css"}
{css href="__AD_CSS__/sku_style.css" /}
{/block}
{block name="body"}
{volist name="sku" id="v"}
<div class="layui-form-item attr-key-item" style="display: none;">
        <input type="hidden" name="attr_key[{$key}]" value="{$key}"  class="layui-input attr-key">
    <div class="attr-vals">
        <div class="layui-inline">
            <div class="layui-input-inline">
            	{volist name="v" id="vv"}
            	{in name="$key" value="$g_sku"}
                <input attr_val_id="{$key}" type="hidden" name="attr_val[{$key}][{$key}]" value="{$vv}" lay-verify="required" class="attr-val layui-input">
                {/in}
                {/volist}
            </div>
        </div>
    </div>
</div>
{/volist}
<form class="layui-form">
	<div class="layui-form-item" id="sku-table"></div>
	<div class="layui-form-item">
		<div class="layui-input-block">
		 <button class="layui-btn" lay-submit="myForm" lay-filter="myForm">立即提交</button>
		</div>
	</div>
</form>
{/block}
{block name='js'}
<script type="text/javascript">
    // layui 公共配置
    const layconfig = {
        base: 'layui/js/',
        version: true,
        debug: true,
    };
</script>
<script type="text/javascript">
    const init = function (options) {
        var _modules = options.modules || [];
        _modules = _modules.concat('layer', 'form', 'element');

        layui.config(layconfig).use(_modules, function (opt) {

            var form = layui.form,
                laytpl = layui.laytpl,
                element = layui.element;

            // 其他事件
            if (options.exec) {
                options.exec(layui);
            }

            form.render();
        });
    };
</script>
<script type="text/javascript">
    $(function () {
        var opt = {
            modules: ['table', 'form', 'element', 'laytpl', 'tree'],
            exec: function (layui) {
                // -- 商品规格开始 --
                // 添加自定义 attr key
                var already_set_sku_vals = {};      // 已经设置的SKU值数据
                var arr_sku = {};                   // 已经设置的SKU值数据
                var attr_key_id = '';               // 自定义 attr key id
                var attr_key_sort = 0;              // 自定义 attr key sort
                var attr_val_id = '';               // 自定义 attr val id
                var attr_val_sort = 0;              // 自定义 attr val sort
                var tpl_attr_key_model = $("#tpl-attr-key-model").html();
                attr_key_sort++;
                var data = {attr_key_id: attr_key_id, attr_val_id: attr_val_id, attr_key_sort: attr_key_sort};
                layui.laytpl(tpl_attr_key_model).render(data, (html) => {
                    $("#sku-container").append(html);   // 添加到该按钮的前面
                    layui.form.render('checkbox');
                    initSkuTable();
                });
                // 绘制表格
                function initSkuTable() {
                    get_already_set_sku_vals();     // 获取已经设置的SKU值
                    var attrs =  [];                // 存放属性数组
                    var total_row = 1;              // 总行数
                    var sku_table_dom = "";         // sku表格dom
 
                    // 获取元素类型
                    $(".attr-key-item").each(function(index, item) {
                        var attr_key = {};
                        attr_key.attr_key = $(item).find(".attr-key").val();
 
                        var attr_vals = [];
                        $(item).find('.attr-val').each(function(index, item) {
 
                            var val = $(item).val();
                            if (val == undefined || val == "") {
                                return;
                            }
                            var attr_val = {};  // attr val对象
                            attr_val.attr_key_id = $(this).attr("attr_key_id");
                            attr_val.attr_val_id = $(this).attr("attr_val_id");
                            attr_val.attr_val = val;
                            attr_vals.push(attr_val);
                        });
 
                        if (attr_vals && attr_vals.length > 0) {
                            total_row = total_row * attr_vals.length;
                            attr_key.attr_vals = attr_vals;         // sku值数组
                            attrs.push(attr_key);                   // 保存进数组中
                        }
                    });
 
                    sku_table_dom = "<table class='layui-table skuTable'><thead><tr>";
                    // 创建表头
                    for(var i = 0 ; i < attrs.length ; i ++){
                        sku_table_dom += '<th>'+attrs[i].attr_key+'</th>';
                    }
                    sku_table_dom += '<th>价格</th><th>库存</th>';
                    sku_table_dom += "</thead></tr>";
 
                    // 循环处理表体
                    for(var i = 0 ; i < total_row ; i ++){ //总共需要创建多少行
                        var curr_row_doms = "";
                        var row_count = 1;      // 记录行数
                        var attr_key_ids = [];  // 记录 attr key id
                        var attr_val_ids = [];  // 记录 attr val id
                        var attr_key_arr = [];  // 记录 attr key
                        var attr_val_arr = [];  // 记录 attr val
 
                        for(var j = 0 ; j < attrs.length ; j ++) {
                            var attr_vals = attrs[j].attr_vals;                   // attr val 数组
                            var attr_vals_len = attr_vals.length;                 // attr val 长度
                            row_count = (row_count * attr_vals_len);              // 目前的生成的总行数
                            var an_inter_bank_num = (total_row / row_count);      // 跨行数
                            var point = ((i / an_inter_bank_num) % attr_vals_len);
                            attr_key_arr.push(attrs[j].attr_key);
                            if (0  == (i % an_inter_bank_num)) {
                                // 需要创建td
                                curr_row_doms += '<td rowspan='+an_inter_bank_num+'>' + attr_vals[point].attr_val + '</td>';
                                attr_val_arr.push(attr_vals[point].attr_val);
                                attr_val_ids.push(attr_vals[point].attr_val_id);
                                attr_key_ids.push(attr_vals[point].attr_key_id);
                            }
                            else{
                                // 当前单元格为跨行
                                attr_val_arr.push(attr_vals[parseInt(point)].attr_val);
                                attr_val_ids.push(attr_vals[parseInt(point)].attr_val_id);
                                attr_key_ids.push(attr_vals[parseInt(point)].attr_key_id);
                            }
                        }
 
                        var str_val_ids = attr_val_ids.toString()


                		var already_set_sku_price = ''; // 已经设置的SKU价格
               	 		var already_set_sku_stock = ''; // 已经设置的SKU库存

                        

                        if(already_set_sku_vals){
                            var curr_group_sku_val = already_set_sku_vals[str_val_ids];//当前这组SKU值

                            if(curr_group_sku_val){
                                already_set_sku_price = curr_group_sku_val.sku_price;
                                already_set_sku_stock = curr_group_sku_val.sku_stock;
                            }
                        }
 
                        sku_table_dom += '<tr attr_val_ids="'+attr_val_ids+'" class="sku_table_tr">' + curr_row_doms +
                            '<td><input type="number" step="0.01" min="0.01"  name="sku_price" class="layui-input" value="'+already_set_sku_price+'"/></td>' +
                            '<td><input type="number" step="1" min="1" name="sku_stock" class="layui-input" value="'+already_set_sku_stock+'"/></td>' +
                            '</tr>';
                    }
                    $("#sku-table").html(sku_table_dom);
                    get_already_set_sku_vals();
                    layui.form.render("checkbox");
                }
                function get_already_set_sku_vals(){
                    already_set_sku_vals = <?=$goodsku?>;
                    arr_sku = {};
                    //获取设置的SKU属性值
                    $("tr.sku_table_tr").each(function() {
                        var sku_price = $(this).find("input[name=sku_price]").val();    // SKU价格
                        var sku_stock = $(this).find("input[name=sku_stock]").val();    // SKU库存
                        if (sku_price || sku_stock) {
                            // 已经设置了全部或部分值
                            var attr_val_ids = $(this).attr("attr_val_ids");    // SKU值id集合
                            // var attr_val_names = $(this).attr("attr_val_names");//SKU值name集合
                            already_set_sku_vals[attr_val_ids] = {
                                "sku_price" : sku_price,
                                "sku_stock" : sku_stock,
                            };
                            arr_sku[attr_val_ids] = {
                                "sku_price" : sku_price,
                                "sku_stock" : sku_stock,
                            }
                        }
                    });
                }
 
                layui.form.on('checkbox(unify-price)', function (data) {
                    var unify_price = $("input[name=unify_price]").val();
                    if (data.elem.checked) {
                        $("input[name=sku_price]").val(unify_price);
                    }
                    get_already_set_sku_vals();
                });
 
                layui.form.on('checkbox(unify-stock)', function (data) {
                    var unify_stock = $("input[name=unify_stock]").val();
                    if (data.elem.checked) {
                        $("input[name=sku_stock]").val(unify_stock);
                    }
                });
 
                // -- 商品规格结束 --
                layui.form.on('submit(myForm)', function () {
                    get_already_set_sku_vals();
                    var data = $('#myForm').serialize();
                    $.ajax({
                        url: '{:request()->url()}',
                        method: 'POST',
                        data: arr_sku,
                        dataType: 'json',
                        success: function(res){
                            layer.msg(res.msg);
                            //刷新当前页面
                            setTimeout(function () {
			                    parent.location.reload();
			                }, 1000);
                        }
                    });
                    return false;
                });
            }
        };
        init(opt);
    });
 
</script>
<script type="text/html" id="tpl-attr-key-model">
    <div class="layui-form-item attr-key-item">
        <div class="sku-title">
            <input type="text" name="attr_key[{{d.attr_key_id}}]" placeholder="规格名称，例如：颜色，尺寸" class="layui-input attr-key">
        </div>
        <div class="attr-vals">
            <div class="layui-inline">
                <div class="layui-input-inline">
                    <input attr_val_id="{{d.attr_val_id}}" attr_key_id="{{d.attr_key_id}}" type="text" name="attr_val[{{d.attr_key_id}}][{{d.attr_val_id}}]" placeholder="例如：白色" lay-verify="required" class="attr-val layui-input">
                </div>
            </div>
        </div>
    </div>
</script>
<script type="text/html" id="tpl-attr-val-model">
    <div class="layui-inline attr-vals-item">
        <div class="layui-input-inline">
            <input attr_val_id="{{d.attr_val_id}}" attr_key_id="{{d.attr_key_id}}" type="text" name="attr_val[{{d.attr_key_id}}][{{d.attr_val_id}}]" class="attr-val layui-input">
        </div>
    </div>
</script>
{/block}